package javango.forms.widgets;

import java.util.Map;

/**
 * Widget that allows formatting of decimal numbers,  specifically you can indicated the number of decimal places to be displayed.
 * 
 * @author john
 *
 */
public class DecimalInputWidget extends TextInputWidget {

	private Integer decimalPlaces;
	
	public DecimalInputWidget() {
		super();
	}

	public DecimalInputWidget(Map<String, Object> attrs) {
		super(attrs);
	}

	public void setDecimalPlaces(Integer decimalPlaces) {
		this.decimalPlaces = decimalPlaces;
	}
	
	/**
	 * Return the correct string representation of the provided double value.
	 * @param value
	 * @return
	 */
	protected String format(Double value) {
		String formatString = String.format("%%.%df", decimalPlaces);
		return String.format(formatString, value);
	}
	
	@Override
	public String asText(Object value) {
		if (value instanceof Double && decimalPlaces != null) {
			return format((Double)value);
		} else if (value instanceof Double[]) {
			Double[] values = (Double[])value;
			if (values.length >0) {
				return format(values[0]);
			} else {
				return "";
			}
		}
		return super.asText(value);
	}
	
	@Override
	public String render(String name, Object value, Map<String, Object> attrs) {
		if (value instanceof Double && decimalPlaces != null) {
			value = format((Double)value);
		} else if (value instanceof Double[]) {
			Double[] values = (Double[])value;
			if (values.length >0) {
				return render(name, values[0], attrs);
			} else {
				return render(name, null, attrs);
			}
		}
		return super.render(name, value, attrs);
	}
	
}
